<?php
namespace Admin\Controller;
use Common\Controller\AuthController;
use Think\Auth;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;
use Common\Tool\Tool;
use Admin\Model\AdminModel;
use Admin\Model\AdminGroupAccessModel;
use Admin\Model\AuthGroupAccessModel;

//后台管理员
class AdminController extends AuthController
{
	 //用户列表
     public function admin_list()
     {
    	$m = M('Admin');
    	$nowPage = isset($_GET['p'])?$_GET['p']:1;
    	
    	// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
    	$data = $m->order('id DESC')->page($nowPage.','.PAGE_SIZE)->select();
    	$auth = new Auth();
    	foreach ($data as $k=>$v){
    		$group = $auth->getGroups($v['id']);
    		$data[$k]['group'] = $group[0]['title'];
    	}
    	//分页
    	$count = $m->where($where)->count(id);		// 查询满足要求的总记录数
    	$page = new \Think\Page($count,PAGE_SIZE);		// 实例化分页类 传入总记录数和每页显示的记录数
    	$show = $page->show();		// 分页显示输出
    	$this->assign('page',$show);// 赋值分页输出
    	$this->assign('data',$data);
    	$this->display();
    }
	
    //检查账号是否已注册
    public function check_account()
    {
    	$m = M('admin');
    	$where['account'] = I('account');	//账号
    	$data = $m->field('id')->where($where)->find();
    	if(empty($data)){
    		$this->ajaxReturn(0);   //不存在
    	}else{
    		$this->ajaxReturn(1);	//存在
    	}
    }
    
    /**
     * 保存 添加的管理员 
     */
    public function addAdmin()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('group_id')), false, array('group_id', 'account', 'password')) ? true : $this->error('参数错误');
       
        $model = AdminModel::getInitnation();
        $isHave = $model->isHaveUser($_POST['account']);
        
        $this->alreadyInData($isHave, '已存在该用户');
        $_POST['password'] = md5($_POST['password']);
        //添加用户
        $adminId  = $model->add($_POST);
        $this->prompt($adminId, null, '添加失败');
        
        //分配用户组
        AuthGroupAccessModel::getInitnation()->add(array(
            'uid'      => $adminId,
            'group_id' => $_POST['group_id']
        ))? $this->ajaxReturn(1):$this->ajaxReturn(2);	//分配用户组失败
    }
   
    //添加用户
    public function admin_add()
    {
		$data = AuthGroupModel::getInitnation()->getAuthGroupById('id,title');
		$this->assign('data',$data);
		$this->display();
    }
   
    /**
     * 保存编辑 
     */
    public function saveAudit()
    {
        Tool::checkPost($_POST, array(
            'is_numeric' => array(
                'id', 'group_id', 'status'
        )), true, array('id', 'group_id', 'status'))? true : $this->error('参数错误');
       
        $this->prompt($_POST['status'] >= 0, null, '状态码不正确');
        //修改所属组
        $access = AuthGroupAccessModel::getInitnation();
        $result = $access->getAuthGroupById('uid', array('uid' => $_POST['id']), 'find');
        $this->prompt($result, 'uid', '用户信息错误');
        
        
        $status = AuthGroupAccessModel::getInitnation()->save($_POST, array('where' => array('uid' => $_POST['id'])));
        
        $result = AdminModel::getInitnation()->save($_POST);
        
        ($result === false)? $this->error('修改失败'): $this->success('修改成功');
    }
    
    //编辑
    public function admin_edit()
    {
		Tool::checkPost($_GET, array('is_numeric' => array('id')), false, array('id')) ? true : $this->error('参数错误'); 		
		//获取当前所属组
		$pk = AdminModel::getInitnation()->getPk();
		
		$reuslt = AdminModel::getInitnation()->getLoginUserInfo(array($pk => $_GET['id']), 'account,id,status');
		
		$this->prompt($reuslt, 'account', '没有该用户信息');
		$auth = new Auth();
		$group = $auth->getGroups($reuslt['id']);
		
		//处理数组
		Tool::connect('Mosaic');
		$group = Tool::parseToArray($group);
		$this->assign('vo',array_merge($reuslt,$group));
		//获取所有组
		$group = AuthGroupModel::getInitnation()->getAuthGroupById('id,title');
		$this->assign('group',$group);
		$this->display();
    }
    
    //删除用户
    public function admin_del()
    {
     	$id = $_POST['id'];		//用户ID
    	if($id == 1){
    		$this->ajaxReturn(0);	//不允许删除超级管理员
    	}
    	$m = M('auth_group_access');    	
    	$m->where('uid='.$id)->delete();   //删除权限表里面给的权限
    	    	
    	$m = M('admin');
    	$result = $m->where('id='.$id)->delete();
    	if ($result){
    		$this->ajaxReturn(1);	//成功
    	}else {
    		$this->ajaxReturn(0);	//删除失败
    	}
    }

    //角色-组
    public function auth_group(){
    	$m = M('auth_group');
    	$data = $m->order('id DESC')->select();
    	$this->assign('data',$data);
    	$this->display();
    }
    
    
    /**
     * 保存 
     */
    public function addAudit()
    {
        Tool::checkPost($_POST, (array)null, false, array('title', 'rules')) ? true : $this->error('参数错误');
        $_POST['rules'] = implode(',', $_POST['rules']);
        $status = AuthGroupModel::getInitnation()->add($_POST);
        $status ? $this->success('添加成功'):$this->error('添加失败');
    }
    //添加组
    public function group_add()
    {
		$data = $this->getAduit();
    	$this->assign('data',$data);	// 顶级
		$this->display();
    }
    
    public function saveEdit()
    { 
        Tool::checkPost($_POST, array('is_numeric' => array('id')), true, array('id', 'title', 'rules')) ? true : $this->error('参数错误');
        $_POST['rules'] = implode(',', $_POST['rules']);
        $status = AuthGroupModel::getInitnation()->save($_POST);
        $status ? $this->success('修改成功'):$this->error('修改失败');
    }
    //编辑组
    public function group_edit()
    {
        Tool::checkPost($_GET, array('is_numeric' => array('id')), true, array('id')) ? true : $this->error('参数错误');
		
        $reuslt = AuthGroupModel::getInitnation()->getAuthGroupById('id,title,rules', array('id' => $_GET['id']), 'find');
		
        $data = $this->getAduit();
        $this->assign('data',$data); 
		$this->assign('reuslt',$reuslt);
		$this->display();    		
    }
    
    /**
     * 获取权限 
     */
    private function getAduit($field  = 'id,title,pid')
    {
        Tool::connect('parseString');
        $data          = AuthRuleModel::getInitnation()->getAuthGroupById($field, 'pid=0');
        $towChildren   = AuthRuleModel::getInitnation()->getTwoChildren($data, $field);
        $threeChildren = AuthRuleModel::getInitnation()->getTwoChildren($towChildren, $field);
        
        Tool::connect('ArrayParse');
        //合并孙子到爷爷做准备
        $threeChildren = AuthRuleModel::getInitnation()->getGrandFather($threeChildren);
        
        Tool::connect('Tree');
        $data = array_merge($data, (array)$towChildren, (array)$threeChildren);
        $data = Tool::makeTree($data, array(
            'parent_key' => 'pid'
        ));
        
        return $data;
    }
    //删除组
    public function group_del(){
    	$where['id'] = I('id');
    	$m = M('auth_group');
    	if($m->where($where)->delete()){
    		$this->ajaxReturn(1);
    	}else{
    		$this->ajaxReturn(0);
    	}
    }
    /**
     * 添加权限
     */
    public function addJurisdiction()
    {
        Tool::checkPost($_POST, array('pid'), false, array('title', 'name'))? true : $this->error('参数错误');
        (AuthRuleModel::getInitnation()->add($_POST))? $this->success('添加成功'): $this->error('添加失败');	//失败
    }
    //权限列表
    public function auth_rule()
    {
		$field = 'id,name,title,create_time,status,sort,pid';
		$classData = AuthRuleModel::getInitnation()->getAuthGroupById($field);
		
		$data  = AuthRuleModel::getInitnation()->getAuthGroupById($field, 'pid=0');
		
		Tool::connect('parseString');
    	$twoChildren = AuthRuleModel::getInitnation()->getTwoChildren($data, $field);
		
    	//生成树形结构
    	Tool::connect('Tree');
    	
    	$data = Tool::makeTree(array_merge($data, $twoChildren), array(
    	    'parent_key' => 'pid'
    	));
    	
		$this->assign('data',$data);	// 顶级
		$this->classData = $classData;
    	$this->display();
    }
	
	//编辑权限组
	public function auth_rule_edit(){
		if(!empty($_POST)){
			$m = M('auth_rule');
			$_POST['update_time'] = time();
			$result = $m->save($_POST);
			if($result){
				$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
		}else{
			$m = M('auth_rule');
			$where['id'] = $_GET['id'];
			$result = $m->where($where)->find();
			$result['create_time'] = date('Y-m-d H:i:s',$result['create_time']);
			$this->assign('result',$result);
			$this->display();
		}
	}
	
	//导航栏隐藏(导航栏下的侧栏也隐藏)
	public function rule_yin(){
		if(IS_POST){
			$id = I('post.id');
			$auth_rule = M('auth_rule');
			$data['xianshi'] = 1;
			$result = $auth_rule->where('id='.$id)->save($data);
			$resone = $auth_rule->where('pid='.$id)->save($data);
		}
	}
	

    //设置手机号
    public function set_mobile(){
        if(IS_POST){
            foreach ($_POST['mobile'] as $k => $v) {
                if(empty($v)){
                    unset($_POST['mobile'][$k]);
                }
            }
            $data['mobile'] = implode(',',$_POST['mobile']);

            $result = M('set')->where('id=1')->save($data);

            if($result){
                $this->success('设置成功');
            }else{
                $this->error('设置失败');
            }
        }else{
            $result = M('set')->where('id=1')->find();
            $arr = explode(',',$result['mobile']);
            $this->assign('arr',$arr);
            $this->display();
        }

        
    }
    
    /**
     * 支付设置 
     */
    public function payConfig()
    {
        $this->display('pay_config');
    }
    
	
}




